package routers

import (
	"encoding/json"
	"net/http"
	"reflect"
	"strconv"

	"shqsoft.cn/pasnj/base"
	"shqsoft.cn/pasnj/popedom"

	//log "github.com/sirupsen/logrus"
	"github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo"
)

//FindRouter 路由：根据给定的WhereCause获取列表数据
func FindRouter(c echo.Context) error {
	daoName := c.Param("DaoName")
	if daoName == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "daoName不能为空！")
	}
	pageNumberStr := c.Param("PageNumber")
	if pageNumberStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "pageNumber不能为空！")
	}
	pageCountStr := c.Param("PageCount")
	if pageCountStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "pageCount不能为空！")
	}
	permIDStr := c.FormValue("PermID")
	if permIDStr == "" || permIDStr == "undefined" || permIDStr == "null" {
		permIDStr = "0"
	}
	permID, err := strconv.Atoi(permIDStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "PermID必须为整数！")
	}
	var whereCauses []base.WhereCause
	jsonStr := c.FormValue("WhereCauses")
	if jsonStr != "" {
		err := json.Unmarshal([]byte(jsonStr), &whereCauses)
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	var orderItems []base.OrderItem
	jsonStr = c.FormValue("OrderItems")
	if jsonStr != "" {
		err := json.Unmarshal([]byte(jsonStr), &orderItems)
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	if daoName == "CompAccoFlow" {
		var orderItems2 []base.OrderItem
		orderItems2 = append(orderItems2, base.OrderItem{
			FieldName: "FPNO",
			Direction: "ASC",
		})
		orderItems2 = append(orderItems2, orderItems...)
		orderItems = orderItems2
	}
	if daoName == "COMP_CM_BIZ_FEE_SUM_M" {
		var orderItems3 []base.OrderItem
		orderItems3 = append(orderItems3, base.OrderItem{
			FieldName: "ACTL_CHARGE_AMT",
			Direction: "DESC",
		})
		orderItems3 = append(orderItems3, orderItems...)
		orderItems = orderItems3
	}
	if daoName == "COMP_GSZ" || daoName == "CompTyywDrDtip" {
		var orderItems4 []base.OrderItem
		orderItems4 = append(orderItems4, base.OrderItem{
			FieldName: "DRJG",
			Direction: "DESC",
		})
		orderItems4 = append(orderItems4, orderItems...)
		orderItems = orderItems4
	}
	if daoName == "V_DIM_USER" {
		var orderItems5 []base.OrderItem
		orderItems5 = append(orderItems5, base.OrderItem{
			FieldName: "OrderKey",
			Direction: "ASC",
		})
		orderItems5 = append(orderItems5, base.OrderItem{
			FieldName: "DPNM",
			Direction: "DESC",
		})
		orderItems5 = append(orderItems5, orderItems...)
		orderItems = orderItems5
	}
	if daoName == "XWPHDR" {
		var orderItems5 []base.OrderItem
		orderItems5 = append(orderItems5, base.OrderItem{
			FieldName: "DRRQ",
			Direction: "DESC",
		})
		orderItems5 = append(orderItems5, base.OrderItem{
			FieldName: "DRJG",
			Direction: "DESC",
		})
		orderItems5 = append(orderItems5, orderItems...)
		orderItems = orderItems5
	}
	dao, err := base.GetDao(daoName)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	pageNumber, err := strconv.Atoi(pageNumberStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "pageNumber必须为数字")
	}
	pageCount, err := strconv.Atoi(pageCountStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "pageCount必须为数字")
	}
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*UserLoginClaims)
	pTypes, err := popedom.GetUserPermissionTypes(claims.UserID, permID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	listData, err := dao.Find(whereCauses, orderItems, pageNumber, pageCount, claims.UserID, pTypes...)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, listData)
}

//FindAllRouter 查询指定表的所有数据
func FindAllRouter(c echo.Context) error {
	daoName := c.Param("DaoName")
	if daoName == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "daoName不能为空！")
	}
	var orderItems []base.OrderItem
	jsonStr := c.FormValue("OrderItems")
	if jsonStr != "" {
		err := json.Unmarshal([]byte(jsonStr), &orderItems)
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	if daoName == "Role" {
		var orderItems2 []base.OrderItem
		orderItems2 = append(orderItems2, base.OrderItem{
			FieldName: "SortNo",
			Direction: "ASC",
		})
		orderItems2 = append(orderItems2, orderItems...)
		orderItems = orderItems2
	}
	where := c.FormValue("where")
	if where == "" || where == "undefined" || where == "null" {
		where = ""
	}
	dao, err := base.GetDao(daoName)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	listData, err := dao.FindAll(orderItems, where)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, listData)
}

//AddRouter 路由：按照给定的实体类添加数据
func AddRouter(c echo.Context) error {
	dao, entity, err := getDaoAndEntity(c)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	pks, err := dao.Add(entity)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, pks)
}

//DeleteRouter 路由：按照给定的实体类删除数据
func DeleteRouter(c echo.Context) error {
	dao, entity, err := getDaoAndEntity(c)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	count, err := dao.Delete(entity)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, count)
}

//DeletesRouter 路由：按照给定的主键值（[]interface{}）删除数据
func DeletesRouter(c echo.Context) error {
	var pkVal []interface{}
	jsonStr := c.FormValue("PrimaryKeyValues")
	err := json.Unmarshal([]byte(jsonStr), &pkVal)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	daoName := c.Param("DaoName")
	if daoName == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "daoName不能为空！")
	}
	dao, err := base.GetDao(daoName)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	count, err := dao.Deletes(pkVal...)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, count)
}

//SaveDatasRouter 路由：批量保存数据
func SaveDatasRouter(c echo.Context) error {
	daoName := c.Param("DaoName")
	if daoName == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "daoName不能为空！")
	}
	dao, err := base.GetDao(daoName)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	newDatas := dao.GetEntitis()
	jsonStr := c.FormValue("NewDatas")
	if jsonStr != "" {
		err = json.Unmarshal([]byte(jsonStr), newDatas)
	}
	updateDatas := dao.GetEntitis()
	jsonStr = c.FormValue("UpdateDatas")
	if jsonStr != "" {
		err = json.Unmarshal([]byte(jsonStr), updateDatas)
	}
	deleteDatas := dao.GetEntitis()
	jsonStr = c.FormValue("DeleteDatas")
	if jsonStr != "" {
		err = json.Unmarshal([]byte(jsonStr), deleteDatas)
	}
	tx := base.DB.Begin()
	deleteDataArr := reflect.ValueOf(deleteDatas)
	l := deleteDataArr.Elem().Len()
	for i := 0; i < l; i++ {
		deleteData := deleteDataArr.Elem().Index(i).Addr().Interface()
		_, err = dao.Delete(deleteData)
		if err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	newDataArr := reflect.ValueOf(newDatas)
	l = newDataArr.Elem().Len()
	keysMap := make([]map[string]interface{}, l, l)
	for i := 0; i < l; i++ {
		newData := newDataArr.Elem().Index(i).Addr().Interface()
		keys, err := dao.Add(newData)
		if err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
		keysMap[i] = keys
	}
	updateDataArr := reflect.ValueOf(updateDatas)
	l = updateDataArr.Elem().Len()
	for i := 0; i < l; i++ {
		updateData := updateDataArr.Elem().Index(i).Addr().Interface()
		_, err = dao.Update(updateData)
		if err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	tx.Commit()
	return c.JSON(http.StatusOK, keysMap)
}

//UpdateRouter 路由：删除数据
func UpdateRouter(c echo.Context) error {
	dao, entity, err := getDaoAndEntity(c)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	count, err := dao.Update(entity)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return c.JSON(http.StatusOK, count)
}
func getDaoAndEntity(c echo.Context) (base.Dao, interface{}, error) {
	daoName := c.Param("DaoName")
	if daoName == "" {
		return nil, nil, echo.NewHTTPError(http.StatusBadRequest, "daoName不能为空！")
	}
	dao, err := base.GetDao(daoName)
	if err != nil {
		return nil, nil, echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	entity := dao.GetEntity()
	jsonStr := c.FormValue("Entity")
	if jsonStr == "" {
		return nil, nil, echo.NewHTTPError(http.StatusBadRequest, "Entity不能为空！")
	}
	err = json.Unmarshal([]byte(jsonStr), entity)
	if err != nil {
		return nil, nil, echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	return dao, entity, nil
}
